from collections import deque
from typing import *
from math import inf


class Solution:
    def minimumSum(self, nums: List[int]) -> int:
        n = len(nums)
        s = deque()
        for i, v in enumerate(nums):
            while s and v <= s[-1][1]:
                s.pop()
            s.append((i, v))
        mn = nums[0]
        ans = inf
        for i in range(1, n - 1):
            v = nums[i]
            while s[0][0] <= i:
                s.popleft()
            if s[0][1] < v and mn < v:
                ans = min(ans, mn + v + s[0][1])
            mn = min(mn, v)
        return -1 if ans == inf else ans


s = Solution()
print(s.minimumSum(nums=[8, 6, 1, 5, 3]))
